import axios from 'axios'
// eslint-disable-next-line no-unused-vars
import { Notification, MessageBox, Message } from 'element-ui'
// eslint-disable-next-line no-unused-vars
import store from '../store'
import { getToken } from './auth'
// import errorCode from '../utils/errorCode'
import router from '@/router'
import {auth, lock, unLock} from '@/utils/auth'
import {checkLogin} from '@/api/login'
import Vue from 'vue'
// import {getInfo} from '@/api/login'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.NODE_ENV === 'prod' ? 'http://api.mrquin.club' : 'http://localhost:8090',
  // 超时
  timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
  console.log('============================request拦截器开始============================')
  console.log(config.url)
  // 是否需要设置 token
  const isToken = (config.headers || {}).Authorization === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  if (!checkLogin()) {
    return config
  }
  // 如果当前时间节点未到需要刷新的时间，则直接返回config
  if (Date.now() < (parseInt(store.getters.accessTokenExpireDate) - 180 * 1000)) {
    return config
  }
  console.log('获取锁')
  // 如果登录校验未通过，则尝试获取锁进行重授权
  if (lock()) {
    console.log('刷新token')
    authAndRefreshToken()
    if (getToken() && !isToken) {
      config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
  }
  console.log('进入末尾')
  console.log('============================request拦截器结束============================')
  return config
}, error => {
  return Promise.reject(error)
})

async function authAndRefreshToken () {
  await auth().then(res => {
    store.commit('SET_TOKEN', res.data['accessToken'])
    store.commit('SET_TOKEN_EXPIRED', res.data['expireMills'])
  }).catch(() => {
    store.dispatch('ClearCache').then(() => {
      router.push('/login').then(r => {
        Vue.prototype.$notify.error('未登录或登录已过期，即将跳转到登录页')
      })
    })
  }).finally(() => {
    unLock()
    console.log('释放锁，返回config')
  })
}

// 响应拦截器
service.interceptors.response.use(res => {
  // 未设置状态码则默认成功状态
  const code = res.data.code || '00000'
  // 获取错误信息
  // const msg = errorCode[code] || res.data.msg || errorCode['default']
  console.log('响应数据')
  console.log(res)
  let result
  switch (code) {
    case '00000':
      result = res.data
      break
    case 'A0230':
      store.dispatch('ClearCache').then(r => {
        Notification({
          type: 'warning',
          message: res.data.msg,
          title: '请求失败'
        })
        router.push('/login').then(r => {
          store.dispatch('SET_IS_TOKEN_UNEXPIRE', false)
        })
      })
      break
    case 'A0231':
      if (lock()) {
        auth().then(res => {
          store.commit('SET_TOKEN', res.data['accessToken'])
          store.commit('SET_TOKEN_EXPIRED', res.data['expireMills'])
        }).finally(() => {
          unLock()
        })
      }
      break
    default:
      result = Promise.reject(res.data.msg)
  }
  return result
},
error => {
  console.log('err' + error)
  let { message } = error
  if (message === 'Network Error') {
    message = '后端接口连接异常'
  } else if (message.includes('timeout')) {
    message = '系统接口请求超时'
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  }
  Message({
    message: message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
}
)

// function checkTokenExpire () {
//   if (store.getters.logged) {
//     return true
//   }
//   if (!store.getters.currentUserId) {
//     return false
//   }
//   getInfo()
// }

export default service
